<template>
  <el-dialog v-model="dialogFormVisible" @close="handleClose" :close-on-click-modal="false" :title="title"
             width="940px">
    <el-form
        v-loading="editLoading"
        ref="formRef"
        label-width="150px"
        :model="form"
        style="padding: 30px"
        :rules="rules"
    >
      <el-form-item label='广告类型：'  prop='type'>
        <el-select v-model='form.type' placeholder='请选择'>
          <el-option v-for='item in  typeOptions' :key='item.value' :label='item.label'
                     :value='item.value'/>
        </el-select>
      </el-form-item>

      <el-form-item label="广告名称：" prop="name">
        <el-input v-model="form.name" autocomplete="off" maxlength="200" placeholder="名称"/>
      </el-form-item>

      <el-form-item label="广告封面：" prop="cover">
        <kva-upload @success="handleUploadSuccess" path="adverts" ref="imgUploadRef"></kva-upload>
        <p class="ml10" style="margin-left: 10px">建议的图片尺寸：590(宽)*650(高)</p>
      </el-form-item>

      <el-form-item label='跳转模式：' prop='skipModel'>
        <el-select v-model='form.skipModel' placeholder='请选择'>
          <el-option v-for='item in skipModelOptions' :key='item.value' :label='item.label' :value='item.value'/>
        </el-select>
      </el-form-item>
      <el-form-item label='广告链接：' prop='skipValue' v-if="form.skipModel==2">
        <el-input v-model='form.skipValue' placeholder='请输入链接地址' maxlength='200'></el-input>
      </el-form-item>
      <el-form-item label='广告链接标题：' prop='skipTitle' v-if="form.skipModel==2">
        <el-input v-model='form.skipTitle' placeholder='请输入广告标题' maxlength='100'></el-input>
      </el-form-item>

      <el-form-item label='排序：' prop='sorted' >
        <el-input v-model='form.sorted' placeholder='请输入排序' maxlength='10'></el-input>
      </el-form-item>

      <el-form-item label="广告商：" required prop="advertiserName" @click.stop="handleOpenedUploader">
        <el-input v-model="form.advertiserName" readonly maxlength="60" placeholder="广告商">
          <template #append>
            <el-button type="primary" icon="plus" @click.stop="handleOpenedUploader">选择广告商</el-button>
          </template>
        </el-input>
      </el-form-item>


      <el-form-item label='有效时间:' prop='startTime'>
        <label for="start-date-picker">开始日期：</label>
        <el-date-picker
            id="start-date-picker"
            style="margin-right: 10px"
            v-model="form.startTime"
            type="datetime"
            placeholder="选择广告开始日期"
        ></el-date-picker>

        <label for="end-date-picker">结束日期：</label>
        <el-date-picker
            id="end-date-picker"
            v-model="form.endTime"
            type="datetime"
            placeholder="选择广告结束日期"
        ></el-date-picker>

      </el-form-item>
      <el-form-item label="启用状态：" required prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="dialog-footer" style="text-align: center">
        <el-button @click="handleClose" icon="remove">取消</el-button>
        <el-button type="primary" :loading="suLoading" @click="handleSubmit" icon="plus">保存</el-button>
      </div>
      <advertiserment ref='advertisermentUpRef' @select='handleSelectUp'></advertiserment>
    </el-form>
  </el-dialog>
</template>
<script setup>
import {getById, saveUpdate} from '@/api/advert/advert.js'
import KVA from '@/utils/kva.js'
import {formatTimeToStr} from '@/utils/date.js'
const advertisermentUpRef = ref({})
const imgUploadRef = ref({
  isshow: false,
})
const emits = defineEmits(["load"])
// 控制弹窗得显示
const dialogFormVisible = ref(false)
const typeOptions = reactive([
  {label: '首页广告', value: 1},
  {label: '课程广告', value: 2},
  {label: '文章广告', value: 3},
  {label: '个人中心广告', value: 4},
  {label: '文章明细广告', value: 5},
  {label: '课程明细广告', value: 6},
  {label: '悬浮广告', value: 7},
  {label: '小册广告', value: 8},
  {label: '小册明细广告', value: 9},
  {label: '专题广告', value: 10},
  {label: '专题明细广告', value:11},
  {label: '个人社区广告', value: 12},
  {label: '资源广告', value: 13},
  {label: '资源明细广告', value:14},
])

// 这个数据模型
let form = ref({
  status: 1,
  name: '',
  startTime: "",
  endTime: "",
  cover: '',
  type: '',
  skipModel: '',
  skipTitle: '',
  skipValue: '',
  sorted:"",
  datePickerValue: [],
  advertiserId: '',
  advertiserName: ""
})

const handleCloseUploader = () => {
  form.value.advertiserId = ''
  form.value.advertiserName = ''
}

const handleSelectUp = (row) => {
  KVA.notifySuccess("广告主绑定成功!")
  form.value.advertiserId = row.id
  form.value.advertiserName = row.nickname
  advertisermentUpRef.value.handleClose()
}
const handleOpenedUploader = () => {
  advertisermentUpRef.value.handleOpen(form.value?.advertiserId)
}

// 弹出标题
const title = ref("添加")
const editLoading = ref(false)
const suLoading = ref(false)
// 表单ref, 用于提交最终得验证处理
const formRef = ref({})
// 表单验证
const rules = reactive({
  "name": [{required: true, message: '请输入广告名称', trigger: 'blur'}],
  "skipTitle": [{required: true, message: '请输入广告标题', trigger: 'blur'}],
  "skipModel": [{required: true, message: '请选择跳转类型', trigger: 'blur'}],
  "type": [{required: true, message: '请选择广告类型', trigger: 'blur'}],
  "advertiserName": [{required: true, message: '请选择广告商', trigger: 'blur'}],
  "cover": [{required: true, message: '请上传封面', trigger: 'blur'}],
  "startTime": [{required: true, message: '请选择广告有效时间', trigger: 'blur'}],
  "endTime": [{required: true, message: '请选择广告有效时间', trigger: 'blur'}],
  "sorted": [{required: true, message: '请选择广告位置', trigger: 'blur'}],
  "skipValue": [{required: true, message: '请选择链接', trigger: 'blur'}]
})

const skipModelOptions = reactive([
  {label: '无', value: 1},
  {label: '链接', value: 2}
])

// 选择日期时间
const datePickerChange = (dateTimeRangePicker) => {
  form.value.datePickerValue = dateTimeRangePicker || []
  form.value.startTime = formatTimeToStr(dateTimeRangePicker[0])
  form.value.endTime = formatTimeToStr(dateTimeRangePicker[1])
}

const handleUploadSuccess = (data1) => {
  form.value.cover = data1
}

// 打开修改密码的弹窗
const handleOpen = async (opid,type) => {
  // 每次打开头重置
  dialogFormVisible.value = true;
  form.value.type = type
  title.value = "添加"
  if (opid) {
    title.value = "编辑广告"
    editLoading.value = true;
    const resp = await getById(opid)
    editLoading.value = false;
    form.value = resp.data
    imgUploadRef.value.toggleImgcover(form.value.cover)
    form.value.datePickerValue = [form.value.startTime, form.value.endTime];
    title.value = "编辑广告【" + form.value.name + "】"
  }
}

// 保存用户
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.value.skipModel != 2) {
        form.value.skipValue = "";
        form.value.title = "";
      }
      if (form.value.startTime) {
        form.value.startTime = formatTimeToStr(form.value.startTime)
      }
      if (form.value.endTime) {
        form.value.endTime = formatTimeToStr(form.value.endTime)
      }
      suLoading.value = true
      await saveUpdate(form.value)
      suLoading.value = false
      // 提示保存成功
      KVA.notifySuccess(form.value.id ? "更新成功" : "保存成功")
      // 关闭弹窗
      handleClose()
      // 刷新方法
      emits("load")
    }else{
      suLoading.value = false
    }
  })
}

const handleClose = () => {
  title.value = "编辑广告"
  imgUploadRef.value.toggleImgcover('')
  formRef.value.resetFields()
  form.value = {
    id:'',
    status: 1,
    name: '',
    startTime: "",
    endTime: "",
    cover: '',
    type: '',
    skipModel: '',
    skipTitle: '',
    skipValue: '',
    sorted:"",
    datePickerValue: [],
    advertiserId: '',
    advertiserName: ""
  }
  suLoading.value = false
  editLoading.value = false
  dialogFormVisible.value = false
}

// 把弹出打开得方法暴露给父组件进行调用
defineExpose({
  handleOpen
})
</script>
